require(['../config'],()=>{
    require(['template','request','header','footer','jquery'],(template,request,header)=>{
        class Cart{
            constructor(){
                this.shopListWarp=$('#shopListWarp')
                this.cart=JSON.parse(localStorage.getItem('cart')||'[]')
                this.init()
                this.checkesShow()
                this.calcMoney(this.cart)
                this.checkAll()
                this.AllchecksInit()
                this.changeCount()
                this.delShop()
                header.loadHTML().then(_=>{
                    $('.header-right').css({visibility:'hidden'})
                })
                
            }
            init(){
                let words=''
                if(this.cart.length>0){
                    $('#shopListWarp').html(template('ShopList',{ShopList:this.cart}))
                    this.changeCountActive()
                    const index=Math.round(Math.random()*(this.cart.length-1))
                    words=this.cart[index].title.slice(0,3)
                }else{
                    $('.cart-warp .empty-cart').show()
                    words="内衣"
                }
                request.getSearchList(words).then(value=>{
                    const list=value.data.list.slice(0,20)
                    $('#tuijian_shopList_warp').html(template('tuijian_shopList',{tuijianList:list}))
                    this.addTocart(list)
                })

                $('#maybeShowPay').on('click',function(){
                    if(document.cookie){
                        alert('付款成功，稍后为您安排发货！！！')
                    }else{
                        location.href='/html/login.html'
                    }
                })
            }

           
           addTocart(datas){
               $('#tuijian_shopList_warp').on('click',(e)=>{
                this.cart=JSON.parse(localStorage.getItem('cart')||'[]')
                if(e.target.className==='add-to-cart'){
                  const id=$(e.target).parents('li').data('id')
                  const shop = datas.find(val=>{
                              return val.id===id
                            })
                  if(this.cart.length>0){
                    const isRepeat = this.cart.find(val=>{
                      return val.id===id
                    })
                    if(isRepeat){
                      this.addType=2
                      isRepeat.count++
                    }else{
                      this.addType=1
                      this.cart.push({...shop,count:1,checked:true})
                    }
                    localStorage.setItem('cart',JSON.stringify(this.cart))
                 }else{
                  this.cart.push({...shop,count:1,checked:true})
                  localStorage.setItem('cart',JSON.stringify(this.cart))
                  this.addType=1
                 }
                //判断更新shop的类型
                if(this.addType===1){
                  //更新顶部购物车
                  header.showHeade()
                  $('#header-cart-warp').append(
                    `<li data-id='${shop.id}'>
                        <a href="/html/shopinfo.html?id=${shop.id}"><img src="${shop.image}"></a>
                        <div class="shopinfo">
                            <span>${shop.title.slice(0,10)}</span>
                            <p class="color">${shop.couponValue}</p>
                            <p class="priceinfo"><span class="price">${shop.price}</span><span class="count">x&nbsp;1</span></p>
                        </div>
                        <span class="del">x</span>
                        </li>`)
                     //更新列表
                     $('#shopListWarp').append(
                      `<li data-id='${shop.id}'>
                          <div class="checked">
                              <input type="checkbox" class="checkActive" checked="">
                          </div>
                          <div class="item-left">
                              <div class="item">
                                  <a href="/html/shopinfo.html?id=${shop.id}">
                                      <img src="${shop.image}">
                                  </a>
                                  <div class="des">
                                      <a href="javascript:;">${shop.title.slice(0,8)}...</a>
                                      <p></p>
                                  </div>
                              </div>
                          </div>
                          <div class="item-right">
                              <div class="onePrice">￥${shop.price}</div>
                              <div class="count">
                                  <i class="decriment">-</i>
                                  <i class="num">1</i>
                                  <i class="increment">+</i>
                              </div>
                              <div class="price">
                                  <span>￥${shop.price}</span>
                              </div>
                              <div class="clear"><a class='delOneClassShop'>X</a></div>
                          </div>
                      </li>`
                      )
                    this.checkesShow()
                    this.calcMoney(this.cart)
                    header.topCart(this.cart)
                    this.AllchecksInit()
                    this.changeCount()
                    this.changeCountActive()
                }else if(this.addType===2){
                  //更新顶部对应数据
                    const el = $('#header-cart-warp').children('li').filter(function(){
                                return $(this).data('id')==id
                            })
                    el.find('.count')[0].innerText=1+el.find('.count')[0].innerText*1
                  //更新列表数据
                    const el2 = $('#shopListWarp').children('li').filter(function(){
                      return $(this).data('id')==id
                    })
                    el2.find('.num')[0].innerText=1+el2.find('.num')[0].innerText*1
                    this.calcMoney(this.cart)
                    header.topCart(this.cart)
                    this.AllchecksInit()
                    this.changeCount()
                    this.changeCountActive()
                }
                //显示隐藏提示信息
                $(e.target).prev().show()
                setTimeout(()=>{
                    $(e.target).prev().hide()
                  },500)
                }
              })
           }

            delShop(){
                const _this=this
                let target=null
                let delType=0
                $('#shopListWarp').on('click',function(e){
                    if(e.target.className==='delOneClassShop'){
                        $('.delShop').show()
                        target=$(e.target)
                        delType=1
                    }
                })
                $('.delShop .sure').on('click',function(){
                    $('.delShop').hide()
                    if(delType===1){//删除单个数据
                        const id=target.parents('li').data('id')
                        //更改数据
                        _this.cart = _this.cart.filter(val=>{
                                return val.id!=id
                        })
                    }else if(delType===2){//删除选中数据
                         //更新数据
                        _this.cart = _this.cart.filter(val=>{
                            return val.checked===false
                        })
                    }
                    //存
                    localStorage.setItem('cart',JSON.stringify(_this.cart))
                    //更新页面
                    _this.calcMoney(_this.cart)
                    _this.AllchecksInit()
                    header.topCart(_this.cart)
                    header.showHeade()
                    delType===1?target.parents('li').remove():$('#shopListWarp>li .checkActive:checked').parents('li').remove()
                    if(_this.shopListWarp.children().length==0){
                        $('.cart-warp .empty-cart').show()
                        _this.AllchecksInit()
                    }
                    _this.checkAll()
                })
                $('.delShop .refalse').on('click',function(){
                    $('.delShop').hide()
                })
                $('.checkedInfo .delChecked').on('click',function(){
                    $('.delShop').show()
                    delType=2
                })
            }

            checkesShow(){
                const _this=this
                $('.checkActive').on('change',function(){
                    const id=$(this).parents('li').data('id')
                    //修改数据
                    _this.cart = _this.cart.map(val=>{
                        if(val.id===id)val.checked=$(this).prop('checked')
                        return val
                    })
                    //重新存数据
                    localStorage.setItem('cart',JSON.stringify(_this.cart))
                    //修改页面数据
                    _this.calcMoney(_this.cart)
                    _this.AllchecksInit()
                    _this.checkAll()
                })
            }

            checkAll(){
                const _this=this
                const price=$('.checkedInfo .right .price span')
                const classs= $('.checkedInfo .right .num h3 span')
                const count= $('.checkedInfo .right .num h4 span')
                $('#checkAll').on('change',function(){
                    //修改数据
                  _this.cart = _this.cart.map(val=>{
                        val.checked=$(this).prop('checked')
                        return val
                    })
                    //重新存
                    localStorage.setItem('cart',JSON.stringify(_this.cart))
                    //改page数据
                    if($(this).prop('checked')){
                        _this.calcMoney(_this.cart)
                    }else{
                        price.html('￥'+'0.00')
                        classs.html(0)
                        count.html(0)
                    }
                    $('.checkActive').prop('checked',$(this).prop('checked'))
                })
            }

            calcMoney(cart){
              const price=$('.checkedInfo .right .price span')
              const classs= $('.checkedInfo .right .num h3 span')
              const count= $('.checkedInfo .right .num h4 span')
              const info =cart.reduce((info,shop)=>{
                  if(shop.checked){
                    info.money+=shop.count*shop.price
                    info.count+=shop.count
                    info.class++
                  }
                  return info
                },{money:0,count:0,class:0})
                price.html('￥'+info.money.toFixed(2))
                classs.html(info.class)
                count.html(info.count)
               
            }

            AllchecksInit(){
               const isAllCheck = this.cart.every(val=>val.checked)
               if(this.cart.length==0){
                $('#checkAll').prop('checked', false)
               }else{
                $('#checkAll').prop('checked', isAllCheck)
               }
              
            }

            changeCountActive(){
                this.counts=$('#shopListWarp>li .item-right .num')
                this.counts.each((i,val)=>{
                    if( this.counts.eq(i).html()>1){
                        this.counts.eq(i).prev().removeClass('disable')
                    }else if(this.counts.eq(i).html()==1){
                        this.counts.eq(i).prev().addClass('disable')
                    }
                })
            }

            changeCount(){
                const $decriment=$('.decriment')
                const $increment=$('.increment')
                const _this=this
                $decriment.on('click',function(){
                    if($(this).siblings('.num').html()==2){
                        $(this).addClass('disable')
                    }
                    if($(this).siblings('.num').html()==1){
                        return
                    }
                    _this.changeCountMethod(false,this)
                })
                $increment.on('click',function(){
                    $(this).prevAll('.decriment').removeClass('disable')
                    _this.changeCountMethod(true,this)
                })
            }
            changeCountMethod(boolean,target){//true代表+ false代表减
                 //修改对应的count
                 const id = $(target).parents('li').data('id')
                 let prices=0
                 let count=0
                 this.cart = this.cart.map(val=>{
                     if(val.id===id){
                         boolean? val.count++: val.count--
                         count=val.count
                         prices=val.count*val.price
                     }
                     return val
                 })
                 //存
                 localStorage.setItem('cart',JSON.stringify(this.cart))
                 //更新页面
                 this.calcMoney(this.cart)
                 $(target).parent().next().children('span').html(prices.toFixed(2))
                 $(target).siblings('.num').html(count)
            }
            
        }
        new Cart()
    })
})